#!/bin/python
#-*- coding:utf-8 -*-
# Filename:    main.py
# Revision:    1.0
# Date:        2012-06-14
# Author:      simonzhang
# web:         www.simonzhang.net
# Email:       simon-zzm@163.com
### END INIT INFO
import sys
import os
import random
import tornado.ioloop
import tornado.locale
import tornado.web
import time
import zipfile
from dbmodel import *
from interface import *


def check_agent_get_file_name(_user_agent, _file_name):
    if "MSIE 9.0" in _user_agent:
        file_name = _file_name.split('\\')[-1]
    else:
        file_name = _file_name
    return file_name


class ZipUploadHandler(BaseHandler):
    @tornado.web.authenticated
    def post(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        _get_user_manage_project = if_get_user_project(_get_user)
        _get_project_name = self.get_argument("select")
        _lock_status = odb_upload_deploy_lock(_get_project_name)
        if int(_lock_status['upload_lock']) == 1:
            self.render("templates/mycontext.html", domain=_domain, \
                                                    title=_title, \
                                                    username = _get_user, \
                                                    items=_get_user_left_menu,\
                                                    error_context=["上传操作被锁。", \
                                                                   "稍后再试或与管理员联系。"])
            return 0
        _package_time = time.strftime('%Y%m%d%H%M%S')
        _get_local_package = "%s_%s" % (_get_project_name, _package_time)
        idb_make_package_lock(_get_project_name, _package_time)
        if u"%s" % _get_project_name == u"选择项目":
            _now_time = time.strftime('%Y%m%d%H%M%S')
            idb_make_package_unlock(_get_project_name, _now_time) 
            self.render("templates/mycontext.html", domain=_domain, \
                                                    title=_title, \
                                                    username = _get_user, \
                                                    items=_get_user_left_menu, \
                                                    error_context=["选择好项目，不然我要崩溃了"])
            return 0
        tmp_package_name='project/TMP_%s_%s.zip' % (_get_project_name, _get_local_package)
        try:
            get_data = self.request.files['tmpfile'][0]['body']
        except:
            self.render("templates/mycontext.html", domain=_domain, \
                                                    title=_title, \
                                                    username = _get_user, \
                                                    items=_get_user_left_menu, \
                                                    error_context=["压缩文件损坏。"])
        _tmp_get = open(tmp_package_name, "ab")
        _tmp_get.write(get_data)
        _tmp_get.close()
        if zipfile.is_zipfile(tmp_package_name) == False:
            os.remove('%s' % tmp_package_name)
            _now_time = time.strftime('%Y%m%d%H%M%S')
            idb_make_package_unlock(_get_project_name, _now_time) 
            self.render("templates/mycontext.html", domain=_domain, \
                                                    title=_title, \
                                                    username = _get_user, \
                                                    items=_get_user_left_menu, \
                                                    error_context=["上传的不是zip文件"])
            return 0
        _get_mark = self.get_argument("textmark")
        from shutil import copy, copytree, rmtree
        if not os.path.isdir('project/%s' % _get_project_name):
            os.mkdir('project/%s' % _get_project_name)
        else:
            os.system('/bin/cp -r project/%s project/%s_bak' % (_get_project_name, \
                                                           _get_local_package))
        try:
           _all_package = self.get_argument("allpackage")
        except:
           _all_package = 'off'
        if _all_package == "on":
            os.system('/bin/rm -rf project/%s' % _get_project_name)
            os.mkdir('project/%s' % _get_project_name)
        _deploy_status = '0'
        _tmp_rand_packe_name = "TMP_%s_%s" % (_get_project_name, random.randint(00000, 99999))
        os.system("/usr/bin/unzip -o %s -d project/%s" %(tmp_package_name, _tmp_rand_packe_name))
        from hashlib import md5
        ver_f = open("project/%s/ver.txt" % _tmp_rand_packe_name, "wb")
        ver_f.write("%s\n" % _package_time)
        find_walk=os.walk('project/%s' % _tmp_rand_packe_name)
        for path,dirs,files in find_walk:
            for f in files:
                _base_path = path.replace(_tmp_rand_packe_name, _get_project_name)
                if not os.path.isdir(_base_path):
                    os.makedirs(_base_path)
                file_path = "%s/%s" % (path, f)
                os.system("/bin/cp -f %s %s/" % (file_path, _base_path))
                if f.split('.')[1] not in ['conf', 'properties'] and \
                   f not in ['ver.txt']:
                    _tmp = open(file_path, 'rb').read()
                    get_file_md5 = md5(_tmp).hexdigest()
                    _md5_file_path = file_path.replace('project/%s/' % _tmp_rand_packe_name, '')
                    ver_f.write("%s %s\n" % (get_file_md5, _md5_file_path))
        ver_f.close()
        copy('project/%s/ver.txt' % _tmp_rand_packe_name,
             'project/%s/' % _get_project_name)
        os.system('/bin/cp -rf project/%s/ project/%s' % (_get_project_name, _get_local_package))
        try:
            os.remove(tmp_package_name)
        except:
            pass
        try:
            os.system('/bin/rm -rf project/%s' % _tmp_rand_packe_name)
        except:
            pass
        if os.path.isfile('project/%s/checkdeloyfile.sh' % _get_local_package) == False:
             copy("bin/checkdeloyfile.sh", 'project/%s/' % _get_local_package)
        idb_insert_new_package_name(_get_project_name, _package_time, \
                                    _deploy_status, 1, _get_mark)
        _now_time = time.strftime('%Y%m%d%H%M%S')
        idb_make_package_unlock(_get_project_name, _now_time)
        self.render("templates/returnpage.html", domain=_domain, title=_title, \
                                                 username = _get_user, \
                                                 items=_get_user_left_menu, \
                                                 nextpackage='/index/deploy/')

class OneUploadHandler(BaseHandler):
    @tornado.web.authenticated
    def post(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        _get_user_manage_project = if_get_user_project(_get_user)
        _get_project_name = self.get_argument("select2")
        _lock_status = odb_upload_deploy_lock(_get_project_name)
        if int(_lock_status['upload_lock']) == 1:
            self.render("templates/mycontext.html", domain=_domain, \
                         title=_title, username = _get_user, \
                         items=_get_user_left_menu, \
                         error_context=["上传操作被锁。", \
                                        "稍后再试或与管理员联系。"])
            return 0
        _package_time = time.strftime('%Y%m%d%H%M%S')
        _get_local_package = "%s_%s" % (_get_project_name, _package_time)
        idb_make_package_lock(_get_project_name, _package_time)
        if u"%s" % _get_project_name == u"选择项目":
            self.write(u"别瞎操作")
            return
        from shutil import copy, copytree, rmtree
        if not os.path.isdir('project/%s' % _get_project_name):
            os.mkdir('project/%s' % _get_project_name)
        else:
            os.system('/bin/cp -rf project/%s project/%s_bak' % (_get_project_name, \
                                                                 _get_local_package))
        _deploy_status = '0'
        _tmp_rand_packe_name = "%s_%s" % (_get_project_name, random.randint(00000, 99999))
        try:
            os.mkdir('project/%s' % _tmp_rand_packe_name)
        except:
            os.system('/bin/rm -rf project/%s' % _tmp_rand_packe_name)
            self.render("templates/mycontext.html", domain=_domain, \
                                                    title=_title, \
                                                    username = _get_user, \
                                                    items=_get_user_left_menu, \
                                                    error_context=["临时目录故障，请重试"])
        _get_user_agent = self.request.headers['User-Agent'].split('; ')
        for i in range(1,6):
            _get_text = self.get_argument("textfield%s" % i)
            if len(_get_text)>0:
                _file_path = "project/%s/%s" % (_tmp_rand_packe_name, _get_text)
                if not os.path.exists(_file_path):
                    os.makedirs(_file_path)
                _tmp_file_name = self.request.files['fileField%s' % i][0]['filename']
                file_name = check_agent_get_file_name(_get_user_agent, _tmp_file_name)
                file_data = self.request.files['fileField%s' % i][0]['body']
                if _get_text == ".":
                    _tmp_get = open("project/%s/%s" % (_tmp_rand_packe_name, file_name), "wb")
                else:
                    _tmp_get = open("%s/%s" % (_file_path, file_name), "wb")
                _tmp_get.write(file_data)
                _tmp_get.close()
        _get_mark = self.get_argument("textfield6")
        from hashlib import md5
        ver_f = open("project/%s/ver.txt" % _tmp_rand_packe_name, "wb")
        ver_f.write("%s\n" % _package_time)
        find_walk=os.walk('project/%s' % _tmp_rand_packe_name)
        for path,dirs,files in find_walk:
            for f in files:
                _base_path = path.replace(_tmp_rand_packe_name, _get_project_name)
                if not os.path.isdir(_base_path):
                    os.mkdir(_base_path)
                file_path = "%s/%s" % (path, f)
                os.system("/bin/cp -f %s %s/" % (file_path, _base_path))
                if f.split('.')[1] not in ['conf', 'properties'] and \
                   f not in ['ver.txt']:
                    _tmp = open(file_path, 'rb').read()
                    get_file_md5 = md5(_tmp).hexdigest()
                    _md5_file_path = file_path.replace('project/%s/' % _tmp_rand_packe_name, '')
                    ver_f.write("%s %s\n" % (get_file_md5, _md5_file_path))
        ver_f.close()
        copy('project/%s/ver.txt' % _tmp_rand_packe_name,
             'project/%s/' % _get_project_name)
        os.system('/bin/cp -rf project/%s/ project/%s_%s' % (_get_project_name, \
                                                            _get_project_name, _package_time))
        try:
            os.system('/bin/rm -rf project/%s' % _tmp_rand_packe_name)
        except:
            pass
        if os.path.isfile('project/%s/checkdeloyfile.sh' % _get_local_package) == False:
             copy("bin/checkdeloyfile.sh", 'project/%s/' % _get_local_package)
        idb_insert_new_package_name(_get_project_name, _package_time, \
                                    _deploy_status, 2, _get_mark)
        _now_time = time.strftime('%Y%m%d%H%M%S')
        idb_make_package_unlock(_get_project_name, _now_time)
        self.render("templates/returnpage.html", domain=_domain, \
                                                 title=_title, \
                                                 username = _get_user, \
                                                 items=_get_user_left_menu, \
                                                 nextpackage='/index/deploy/')


class VersionLoadHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        _get_user = self.check_user()
        _domain, _title = if_get_domain_title()
        _get_user_left_menu = if_get_user_left_menu(_get_user)
        _get_user_manage_project = if_get_user_project(_get_user)
        _get_project_name = self.get_argument("verselect1").split("-")[0]
        _get_ver_hand_mod = self.get_argument("verselect2")
        _get_ver_txt = self.get_argument("vertextarea")
        try:
            _del_all_pack = self.get_argument('allpackage')
        except:
            _del_all_pack = "off"
        if u"%s" % _get_project_name == u"选择项目":
            self.write(u"没有选项目，别瞎操作")
            return
        _get_version_config_manage = odb_project_info(_get_project_name)
        if _get_version_config_manage == "ERROR":
            self.write(u"项目错误，别瞎操作")
            return
        _default_manage = _get_version_config_manage["default_version_management"]
        _svn_url = _get_version_config_manage['svn_url']
        _svn_user_name = _get_version_config_manage['svn_username']
        _svn_password = _get_version_config_manage['svn_password']
        _git_url = _get_version_config_manage['git_url']
        _git_user_name = _get_version_config_manage['git_username']
        _git_password = _get_version_config_manage['git_password']
        _get_ver_list = []
        if len(_get_ver_txt.strip()) == 0:
            _get_ver_list.append("high")
        else:
            for lo in _get_ver_txt.split("\r\n"):
             if len(lo) != 0:
                _get_ver_list.append(lo)
        _lock_status = odb_upload_deploy_lock(_get_project_name)
        if int(_lock_status['upload_lock']) == 1:
            self.render("templates/mycontext.html", domain=_domain, \
                                                    title=_title, \
                                                    username = _get_user, \
                                                    items=_get_user_left_menu,\
                                                    error_context = ["上传操作被锁。", \
                                                                     "稍后再试或与管理员联系。"])
            return 0
        _package_time = time.strftime('%Y%m%d%H%M%S')
        _get_local_package = "%s_%s" % (_get_project_name, _package_time)
        idb_make_package_lock(_get_project_name, _package_time)
        from shutil import copy, copytree, rmtree
        if not os.path.isdir('project/%s' % _get_project_name):
            os.mkdir('project/%s' % _get_project_name)
        else:
            os.system('/bin/cp -rf project/%s project/%s_bak' % (_get_project_name, \
                                                                 _get_local_package))
        if u"%s" % _del_all_pack == "on":
            os.system('/bin/rm -rf project/%s' % _get_project_name)
            os.mkdir('project/%s' % _get_project_name)
        _deploy_status = '0'
        import subprocess
        for singler_ver in _get_ver_list:
            _run_comm = "svn checkout "
            if singler_ver != "high":
                _run_comm = "%s -r%s " % (_run_comm, singler_ver)
            if _get_ver_hand_mod == "SVN":
                _url = _svn_url
                _username = _svn_user_name
                _passwd = _svn_password
            elif _get_ver_hand_mod == "GIT":
                _url = _git_url
                _username = _git_user_name
                _passwd = _git_password
            elif _default_manage == 0:
                _url = _svn_url
                _username = _svn_user_name
                _passwd = _svn_password
            elif _default_manage == 0:
                _url = _git_url
                _username = _git_user_name
                _passwd = _git_password
            if len(_username) == 0:
                _run_comm = "%s %s project/%s" % (_run_comm, _url, _get_local_package)
            else:
                _run_comm = "%s %s project/%s --username %s --password %s" % (_run_comm, _url, \
                                                                      _get_local_package, \
                                                                      _username, \
                                                                      if_pass_decryption(_svn_password))
            _run = subprocess.Popen(_run_comm, shell=True, stdout=subprocess.PIPE)
            _run.wait()
        from hashlib import md5
        ver_f = open("project/%s/ver.txt" % (_get_local_package), "wb")
        ver_f.write("%s\n" % _package_time)
        find_walk=os.walk('project/%s' % _get_local_package)
        for path,dirs,files in find_walk:
            if path.find('.svn') > 0:
                os.system('/bin/rm -rf %s' % path)
                continue
            for f in files:
                _base_path = path.replace(_get_local_package, _get_project_name)
                if not os.path.isdir(_base_path):
                    os.makedirs(_base_path)
                file_path = "%s/%s" % (path, f)
                os.system("/bin/cp -f %s %s/" % (file_path, _base_path))
                if f.split('.')[1] not in ['conf', 'properties'] and \
                   f not in ['ver.txt']:
                    _tmp = open(file_path, 'rb').read()
                    get_file_md5 = md5(_tmp).hexdigest()
                    _md5_file_path = file_path.replace('project/%s/' % _get_local_package, '')
                    ver_f.write(u"%s %s\n" % (get_file_md5, _md5_file_path))
        ver_f.close()
        if os.path.isfile('project/%s/checkdeloyfile.sh' % _get_local_package) == False:
             copy("bin/checkdeloyfile.sh", 'project/%s/' % _get_local_package)
        _get_mark = ''
        idb_insert_new_package_name(_get_project_name, _package_time, \
                                    _deploy_status, 3, _get_mark)
        _now_time = time.strftime('%Y%m%d%H%M%S')
        idb_make_package_unlock(_get_project_name, _now_time)
        self.render("templates/returnpage.html", domain=_domain, \
                                                 title=_title, \
                                                 username = _get_user, \
                                                 items=_get_user_left_menu,\
                                                 nextpackage='/index/deploy/')
